from flask import Blueprint, request, jsonify
from conf.comm import sqlalchemy_context
from database import *
from werkzeug.security import generate_password_hash, check_password_hash
import json
import time
import re
import random
from utils.commins import get_redis_conn, send_message
from utils.redisconn import r
from utils.jwt_1 import myjwt

# 蓝图初始化
bp_users = Blueprint('users', __name__)


# 注册功能实现
@bp_users.route('/reg', methods=['POST'])
@sqlalchemy_context()
def reg():
    if request.method == "POST":
        data = request.data
        if not data:
            data = request.form
        # 获取用户输入
        else:
            data = json.loads(request.data)
        if not re.match('^1[3-9]\d{9}$', data['mobile']):
            return jsonify({"code": 10012})
        else:
            # 有效性验证
            # 构造user
            try:
                user = User(username=data['username'], password=generate_password_hash(data['password']),
                            mobile=data['mobile'])
                # 添加user
                db.session.add(user)
                # 保存
                db.session.commit()
                return jsonify({"code": 200})
            except:
                return jsonify({"code": 10010})


@bp_users.route('/sendsms', methods=['POST'])
def sendsms():
    # 传递手机号
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    mobile = data['mobile']
    if not mobile:
        return jsonify({'code': 20010, 'mes': '必须输入手机号'})
    if not re.match('^1[2-9]\d{9}$', mobile):
        return jsonify({"code": 123, "mes": "手机号格式错误"})
    # 用手机号去redis中取验证码，如果能取到返回，请30秒后发
    v = r.get_str(mobile)
    if v:
        return jsonify({"code": 20021, 'mes': '请30秒后发'})
    # 生成验证码
    code = str(random.randint(100000, 999999))
    # 调用短信接口
    flag = send_message(mobile, code, 1)
    if flag:
        # 发送成功，存入redis
        r.set_str(mobile, code, 30)
        # 返回结果（验证码）
        return jsonify({'code': 200, 'smscode': code})
    else:
        return jsonify({'code': 20011, 'mes': '发送失败，请重试'})


@bp_users.route('/mdl', methods=['POST'])
@sqlalchemy_context()
def mdl():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    mobile = data['mobile']
    if re.match('^1[2-9]\d{9}$',mobile):
        code = data['code']
        if r.get_str(mobile) == str(code):
            user = User.query.filter_by(mobile=mobile).first()
            if not user:
                users = User(username=mobile,mobile=mobile)
                db.session.add(users)
                db.session.commit()
            r.del_str(mobile)
            return jsonify({"code": 200, "mes": "登录成功"})
        else:
            return jsonify({"code": 200, "mes": "验证码错误"})
    else:
        return jsonify({"code": 123, "mes": "手机号格式错误"})
#获取现在时间
from datetime import datetime
starttime = datetime.now()

@bp_users.route('/zdl', methods=['POST'])
@sqlalchemy_context()
def zdl():
    data = request.data
    if data:
        data = json.loads(request.data)
        username = data['username']
        password = data['password']
        userdl = User.query.filter_by(username=username).first()
        if userdl:
            if check_password_hash(userdl.password, password):
                token = myjwt.encode_jwt({'id':userdl.id})
                return jsonify({"code": 200, "mes": "登录成功","token":token})
            else:
                asd = Record.query.filter_by(username=username).first()
                if not asd:
                    record = Record(username=data['username'],count=1)
                    db.session.add(record)
                    db.session.commit()
                else:
                    if starttime.timestamp()/3600>=asd.losertime.timestamp()/3600+24:
                        Record.query.filter_by(username=username).update({'count':1,'losertime':starttime})
                        db.commit()
                    if asd.count < 3:
                        Record.query.filter_by(username=username).update({'count':asd.count+1})
                        db.session.commit()
                    else:
                        return jsonify({"code": 1200, "mes": "一天只能修改三次"})
                return jsonify({"code": 1200, "mes": "密码错误"})
        else:

            return jsonify({"code": 1201, "mes": "用户不存在"})
